import React, { Component } from 'react';
import PropTypes from 'prop-types';
import _ from 'lodash';
import { Button, Form, Icon, Input, message, Modal, Spin, Tooltip } from 'antd';
import { addNetConfig, checkNetwork, getNetConfig } from '@api/netConfig';
import { IP_RE } from '@util/constants';

import './index.less';

const prefixCls = 'network-config';
const { Item: FormItem } = Form;

const formItemLayout = {
  labelCol: {
    span: 4
  },
  wrapperCol: {
    span: 20
  }
};

function AddressWrapper({ value, onChange }) {
  return (
    <div className="address-wrapper">
      <Input placeholder="10.1.1.2" value={value} onChange={onChange} />
      <Tooltip title="工作口用于平台正常工作，无需网线连接。" className={`${prefixCls}-ip-tip`}>
        <Icon type="info-circle" />
      </Tooltip>
    </div>
  );
}

AddressWrapper.propTypes = {
  value: PropTypes.string,
  onChange: PropTypes.func
};

class NetworkConfig extends Component {
  constructor(props) {
    super(props);
    this.state = {
      workList: {},
      mgmtList: {},
      pingInfo: [],
      spinning: false,
      buttonLoading: false
    };
  }

  componentDidMount() {
    getNetConfig().then(res => {
      let list = [];
      try {
        list = JSON.parse(_.get(res, 'data.data.result.message', []));
        // eslint-disable-next-line
      } catch (e) {}
      list.forEach(item => {
        if (item.type === 'work') {
          this.setState(
            {
              workList: item
            },
            this.setFieldsValue
          );
        } else {
          this.setState({
            mgmtList: item
          });
        }
      });
    });
  }

  setFieldsValue() {
    const { workList } = this.state;
    const { setFieldsValue } = this.props.form;
    const { nameservers = [] } = workList;
    setFieldsValue({
      ip: workList.address,
      mask: workList.netmask,
      gw: workList.gateway,
      dns: nameservers[0],
      dns2: nameservers[1] ? nameservers[1] : ''
    });
  }

  onClickSubmit = () => {
    const { validateFields } = this.props.form;
    validateFields((errors, values) => {
      if (errors) {
        message.error('有错误，不能提交');
        return;
      }
      Modal.confirm({
        title: '确认修改网络配置吗？',
        okButtonProps: { className: 'button-forwards' },
        onOk: () => {
          this.setState({ buttonLoading: true });
          addNetConfig(values)
            .then(res => {
              const respObj = JSON.parse(_.get(res, 'data.data.result.message')) || {};
              if (!respObj.status) {
                throw new Error('修改失败');
              }
              message.success('修改成功');
              this.setState({ buttonLoading: false });
            })
            .catch(() => {
              message.error('修改失败');
              this.setState({ buttonLoading: false });
            });
        }
      });
    });
  };

  onClickPing = () => {
    const { workList } = this.state;
    const filter = {
      hosts: `["${workList.gateway}"]`
    };
    this.setState({ spinning: true });
    checkNetwork(filter)
      .then(res => {
        this.setState({
          spinning: false,
          pingInfo: _.get(res, 'data.data.host_info', [])
        });
      })
      .catch(() => {
        this.setState({
          spinning: false
        });
      });
  };

  render() {
    const {
      form: { getFieldDecorator }
    } = this.props;
    const { mgmtList, pingInfo, spinning, buttonLoading } = this.state;
    return (
      <div className={prefixCls}>
        <div className={`${prefixCls}-page-title`}>网络配置</div>
        <div className={`${prefixCls}-top-box`}>
          <div className={`${prefixCls}-form`}>
            <Form labelAlign="left">
              <FormItem {...formItemLayout} label="工作网口" colon={false}>
                {getFieldDecorator('ip', {
                  rules: [
                    {
                      required: true,
                      message: '请输入工作网口'
                    },
                    {
                      pattern: IP_RE,
                      message: '您输入的格式有误'
                    }
                  ]
                })(<AddressWrapper />)}
              </FormItem>
              <FormItem {...formItemLayout} label="子网掩码" colon={false}>
                {getFieldDecorator('mask', {
                  rules: [
                    {
                      required: true,
                      message: '请输入子网掩码'
                    },
                    {
                      pattern: IP_RE,
                      message: '您输入的格式有误'
                    }
                  ]
                })(<Input placeholder="255.255.255.0" />)}
              </FormItem>
              <FormItem
                {...formItemLayout}
                label="网&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;关"
                colon={false}
              >
                {getFieldDecorator('gw', {
                  rules: [
                    {
                      required: true,
                      message: '请输入网关'
                    },
                    {
                      pattern: IP_RE,
                      message: '您输入的格式有误'
                    }
                  ]
                })(<Input placeholder="10.0.9.254" />)}
              </FormItem>
              <FormItem {...formItemLayout} label="首选DNS" colon={false}>
                {getFieldDecorator('dns', {
                  rules: [
                    {
                      required: true,
                      message: '请输入首选DNS'
                    },
                    {
                      pattern: IP_RE,
                      message: '您输入的格式有误'
                    }
                  ]
                })(<Input placeholder="10.0.0.2" />)}
              </FormItem>
              <FormItem {...formItemLayout} label="&nbsp;&nbsp;&nbsp;备选DNS" colon={false}>
                {getFieldDecorator('dns2', {
                  rules: [
                    {
                      pattern: IP_RE,
                      message: '您输入的格式有误'
                    }
                  ]
                })(<Input placeholder="10.0.0.2" />)}
              </FormItem>
              <FormItem {...formItemLayout} label={' '} colon={false}>
                <Button
                  type="primary"
                  className={`${prefixCls}-form-btn`}
                  onClick={this.onClickSubmit}
                  loading={buttonLoading}
                >
                  保存修改
                </Button>
              </FormItem>
            </Form>
          </div>
          <div className={`${prefixCls}-message`}>
            <div style={{ marginBottom: 16 }}>
              <span>管理网口</span>
              <span>{mgmtList.address}</span>
              <Tooltip title="管理口用于对设备进行管理，需要网线连接。">
                <Icon type="info-circle" />
              </Tooltip>
            </div>
            <div>
              <span>子网掩码</span>
              <span>{mgmtList.netmask}</span>
            </div>
          </div>
        </div>
        <div>
          <div className={`${prefixCls}-page-title`}>
            测试网络
            <span style={{ color: '#999ea8', fontSize: 14, marginLeft: 16 }}>
              可测试你当前的网络配置是否正确
            </span>
          </div>
          <div className={`${prefixCls}-ping-message`}>
            <Spin tip="加载中" spinning={spinning}>
              {pingInfo.map((item, index) => {
                return (
                  <div key={index}>
                    {item.address} - {item.state}
                  </div>
                );
              })}
            </Spin>
          </div>
          <Button type="primary" onClick={this.onClickPing}>
            测试
          </Button>
        </div>
      </div>
    );
  }
}

NetworkConfig.propTypes = {
  form: PropTypes.object
};

export default Form.create()(NetworkConfig);
